/*
 Copyright (c) Whitemice Consulting, 2007, 2008, 2009
 Adam Tauno Williams <awilliam@whitemice.org>
 License: MIT/X11

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/
using System;
using Whitemice.ZOGI;
using Whitemice.ZOGI.GtkWidgets;
using Whitemice.ZOGI.GtkFolios;

namespace Whitemice.Consonance
{
  public partial class EnterpriseWindow : EntityWindow
  {
		protected Enterprise            enterprise;
		protected EnterpriseFolio       folio;
		//protected ProjectSearchDialog   projectSearchDialog;
		protected ContactSearchDialog   contactSearchDialog;	
    
		public EnterpriseWindow(Enterprise _enterprise) : base(Gtk.WindowType.Toplevel)
		{
			this.Build();
			contactSearchDialog = null;
			//projectSearchDialog = null;
			folio = new EnterpriseFolio();
			folioArea.Child = folio;
			folio.ContactTab.PopupEnabled = true;
			folio.OnTabThaw += new EventHandler(ThawOneLevel);
			
			folio.ContactTab.OnContactEdit += new EntityEventHandler(ContactEdit);
			folio.ContactTab.OnContactRemove += new EntityEventHandler(ContactRemove);
			folio.ContactTab.OnContactUnassign += new EntityEventHandler(ContactUnassign);
			folio.LinksTab.OnEntityPresent += new EntityEventHandler(Present);
			
			Fill(_enterprise);
			//enterprise.OnContactsChanged += new zOGIEntityChangeHandler(folio.ContactTab.Fill);
			ShowAll();
		} /* End Constructor */

    public override Entity Current { get { return enterprise; } }

    protected override void Fill(Entity entity)
    {
      this.EntityNameCheck(entity, typeof(Whitemice.ZOGI.Enterprise));
      enterprise = (entity as Whitemice.ZOGI.Enterprise);
      FreezeToDepth(1);
      Registry.RegisterForNotification(enterprise, this);
      folio.Fill(Current);
      SetTitle();
      if (enterprise.CanModify)
      {
      } else
        {
        }    
    }
		
    public override void ProcessEvent(Whitemice.ZOGI.ServerEvent _event)
    {
      switch(_event.Event)
      {
        case ServerEventType.Update:
          Fill(Current);
          break;
        case ServerEventType.SubordinateChange:
          folio.ContactTab.Fill(enterprise);
          //folio.ProjectTab(enterprise);
          break;
      } // end event-switch 
    } // end ReceiveEvent

    protected override void SaveCallback(Entity entity, Exception exception, object context)
    {
      this.ZLOG(string.Format("SaveCallback(objectId#{0})", entity.ObjectId));
      SetTitle();
      Register(entity);
      folio.Fill(entity);
    }
    
		protected void SetTitle()
		{
			if (enterprise.ObjectId < 0)
			{
				Title = "New Enterprise";
			} else
				{
					Title = "Enterprise#" + 
						enterprise.ObjectId.ToString() + ":" +
						enterprise.Name;
				}
		} // end SetTitle
		
		protected override void Fill()
		{
      //TODO: Honor permissions, make insensitive if enterprise cannot be edited
		  FreezeToDepth(1);
			Registry.RegisterForNotification(enterprise, this);
			folio.Fill(enterprise);
			SetTitle();
			
			folio.Sensitive = enterprise.CanModify;
			if (enterprise.CanModify)
			  contactLink.Sensitive = true;
			  else contactLink.Sensitive = false;
		} // end Fill
		
		protected override bool Take()
		{
			return folio.Take(enterprise);
		} // end Take

		public virtual void ContactAssign(int contactId)
		{
      //TODO: Make Contact Assign Asyncronous
      Entity entity;
      
      this.ZLOG("Entrprise#{0} enterprise assign (Contact#{1})", 
                enterprise.ObjectId,
                contactId);
      if (contactId > 0)
      {
        entity = Server.Connection.Get(contactId, 65535, true);
        if (entity == null)
        {
        } else if (entity is Whitemice.ZOGI.Contact)
          {
            enterprise.Assign(entity);
            folio.ContactTab.Fill(enterprise);
          } else
            {
            }
      }
		} // end AssignContact
		
		public virtual void AssignProject(int _projectId)
		{
      /*
			Entity entity;
			
			if (_projectId > 0)
      {
        entity = ZOGIApplication.Server.Get(_projectId);
        if (entity == null)
        {
        } else if (entity is Whitemice.ZOGI.Project)
          {
          } else
            {
            }
			}
			*/
		} // end AssignProject

		protected virtual void OnRemove (object sender, System.EventArgs e)
		{
		  Remove(enterprise);
		} // end RemoveActivated

		protected virtual void OnApply (object sender, System.EventArgs e)
		{
			Save(enterprise, false);
		} //end OnApplyActivated

		protected virtual void OnClose (object sender, System.EventArgs e)
		{
			Unregister(enterprise, true);
		} // end OnCloseActivated

		protected virtual void OnOk (object sender, System.EventArgs e)
		{
			Save(enterprise, false);
		} // end OnOkClicked

		protected virtual void OnAssignContact(object sender, System.EventArgs e)
		{
		  if(enterprise.CanModify)
		  {
			  if (contactSearchDialog == null)
		  	{
			  	contactSearchDialog = new ContactSearchDialog(
			  		ZOGIUtility.GetWindow(this), 
			  		enterprise.ObjectId,
					  "Assign contact to " + enterprise.Name);
			    contactSearchDialog.SetContactId += 
					  new ContactSearchDialog.SetContactIdHandler(ContactAssign);
				}
				contactSearchDialog.Present();
		  }
		} // end OnAssignContact
		
		protected virtual void ContactEdit(
		  Entity entity,
			object context, 
			Exception exception)
		{
		  if (entity != null)
		    if (!(GUI.RaiseWindow(entity)))
				  new ContactWindow(entity as Contact); 		
		} // end ContactEdit

		protected virtual void ContactRemove(
		  Entity entity,
			object context, 
			Exception exception)
		{
      if (entity == null)
        throw new Exception("Null entity received by ContactRemove");
      this.ZLOG(string.Format("Enterprise#{0} enterprise remove (Contact#{1})", 
                              enterprise.ObjectId,
                              entity.ObjectId));
      if (GUI.RaiseWindow(entity))
      {
        // Object is being viewed, present the window and notify user
        new MessageBox("Object#" + entity.ObjectId.ToString() + " is currently in use.");
      } else
        {
          if (entity.CanModify)
          {
            Freeze();
            DeleteCommand command = new DeleteCommand(entity, 
                                                      RpcPriority.Immediate, 
                                                      null, // no flags
                                                      0, // detail does not matter for deletion
                                                      new string[] { ":remove-child" });
            command.Callback = callback;
            Server.Connection.RunCommand(command);
          } else 
            {
              // Insufficient privileges to delete object
              new MessageBox("You lack sufficient privilages to perform the requested action");
            }
        } // end else-object-is-available
    } // end ContactRemove

		protected virtual void ContactUnassign(
		  Entity entity,
			object context, 
			Exception exception)
		{
		  if (enterprise.CanModify)
		  {
		    enterprise.Unassign(entity);
		  } else new MessageBox("You lack sufficient privilages to perform the requested action");		
		} // end ContactUnassign

		protected virtual void OnDeleteEvent (object o, Gtk.DeleteEventArgs args)
		{
		  Unregister(enterprise, true);
		} // end OnDeleteEvent

		protected virtual void OnRefresh (object sender, System.EventArgs e)
		{
      var command = new FetchCommand(enterprise.ObjectId, 
                                     65535, 
                                     new object[] { ":fill" } );
      command.UseCache = false;
      command.Callback = callback;
      Freeze();
      Server.Connection.RunCommand(command);
		}

    protected override void RemoveCallback(Entity entity, Exception exception, object context)
    {
      this.ZLOG("RemoveCallback");
      if (exception == null)
      {
        Unregister(enterprise, true);
      } else
        {
          new MessageBox(exception);
          Thaw();
        }
    } // end RemoveCallback

    protected override void RemoveChildCallback(Entity entity, Exception exception, object context)
    {
      this.ZLOG("RemoveChildCallback");
      if (exception != null)
        new MessageBox(exception);
      Thaw();
    }
  } // end EnterpriseWindow
} // end namespace
